package com.onemile.net;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.onemile.app.UIGuide;
import com.onemile.data.DXml;
import com.onemile.entity.Session;
import com.onemile.utils.UtiGZip;
import com.onemile.utils.UtiIO;

import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class NetImageLoaderM
{
   // 采用Thread+Handler+MessageQueue+内存缓存

   // 为了加快速度，加入了缓存（主要应用于重复图片较多时，或者同一个图片要多次被访问，比如在ListView时来回滚动）
   private Map<String,Drawable> imageCache = new HashMap<String, Drawable>();
//   private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
   /**
    * 
    * @param imageView
    * @param id 
    * CommodityId,ShopsId
    * @param type
    * 1:商品小图 2：商品大图 3：商家大图
    * @param isUseGZip
    * @param callback
    * @return
    */
   public Drawable loadDrawable(final ImageView imageView, final String id, final int type, final boolean isUseGZip, final ImageCallback callback)
   {
	  // 如果缓存过就从缓存中取出数据
	  try
	  {
		 synchronized (imageCache)
		 {
			if (imageCache.containsKey(id))
			 {
				return imageCache.get(id);
//			   SoftReference<Drawable> softReference = imageCache.get(id);
//				if (softReference.get() != null)
//				{
//				   return softReference.get();
//				}
			 }
		 }
		 
		 // else
		 // {
		 // /**
		 // * 加上一个对本地缓存的查找
		 // */
		 // String bitmapName = imageUrl.substring(imageUrl.lastIndexOf("/") +
		 // 1);
		 // File cacheDir = new File("/mnt/sdcard/test/");
		 // File[] cacheFiles = cacheDir.listFiles();
		 // int i = 0;
		 // for (; i < cacheFiles.length; i++)
		 // {
		 // if (bitmapName.equals(cacheFiles[i].getName()))
		 // {
		 // break;
		 // }
		 // }
		 // //
		 // // if (i < cacheFiles.length)
		 // // {
		 // // return BitmapFactory.decodeFile("/mnt/sdcard/test/" +
		 // bitmapName);
		 // // }
		 // }

		 final Handler handler = new Handler()
		 {
			@Override
			public void handleMessage(Message msg)
			{
			   callback.setImage(imageView, (Drawable) msg.obj);
			}
		 };
		 new Thread()
		 {
			public void run()
			{
			   Drawable drawable = loadImageFromUrl(id, type, isUseGZip);
			   
			   synchronized (imageCache)
			   {
//				   imageCache.put(id, new SoftReference<Drawable>(drawable));
				   imageCache.put(id, drawable);
			   }
			   
			   
			   handler.sendMessage(handler.obtainMessage(0, drawable));
			}

		 }.start();

		 return null;
		 /*
		  * 下面注释的这段代码是Handler的一种代替方法
		  */
		 // new AsyncTask() {
		 // @Override
		 // protected Drawable doInBackground(Object... objects) {
		 // Drawable drawable = loadImageFromUrl(imageUrl);
		 // imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
		 // return drawable;
		 // }
		 //
		 // @Override
		 // protected void onPostExecute(Object o) {
		 // callback.imageLoaded((Drawable) o);
		 // }
		 // }.execute();
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetImageLoaderM_loadDrawable(imageView, imageUrl, callback) ", e);
		 }
		 return null;
	  }
   }

   protected Drawable loadImageFromUrl(String id, int type, boolean isUseGZip)
   {
	  try
	  {
		 DXml data = null;
		 String field = null;
		 switch (type)
		 {
			case 1:
			   data = NetClient.GetCommoditySmallImage(id, isUseGZip);
			   field = "SmallCommodityImg";
			   break;
			case 2:
			   data = NetClient.GetCommodityBigImage(id, isUseGZip);
			   field = "CommodityImg";
			   break;
			case 3:
			   data = NetClient.GetShopBigImage(id, isUseGZip);
			   field = "ShopsImg";
			   break;
		 }

		 if (data != null)
		 {
			byte[] img = null;
			if (isUseGZip)
			{
			   img = UtiGZip.decompress(UtiIO.hexStringToBytes(data.getBody().GetFieldValue(field)));
			}
			else
			{
			   img = UtiIO.hexStringToBytes(data.getBody().GetFieldValue(field));
			}
			return Drawable.createFromStream(new ByteArrayInputStream(img), "src");
		 }
		 return null;
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetImageLoaderM_loadImageFromUrl(imageUrl) ", e);
		 }
	  }
	  return null;
   }

   // 对外界开放的回调接口
   public interface ImageCallback
   {
	  public void setImage(ImageView imageView, Drawable imageDrawable);
   }
}
